package practice.adil.encrypordecryp.JavaEncryptionOne;

import javax.crypto.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

/**
 * Created by 李园 - Adil on 2017/12/18.
 */
public class EncryptionAES {
    // KeyGenerator 提供对称生成器功能，支持各种算法
    private KeyGenerator keyGenerator;
    // SecretKey 负责保存对称密钥
    private SecretKey ddKey;
    // Cipher 负责加密或解密工作
    private Cipher c;
    // cipherKey 保存加密信息
    private  byte[] cipherByte;

    public EncryptionAES() throws NoSuchAlgorithmException, NoSuchPaddingException {
        Security.addProvider(new com.sun.crypto.provider.SunJCE());
        keyGenerator = KeyGenerator.getInstance("AES");
        ddKey  = keyGenerator.generateKey();
        c = Cipher.getInstance("AES");
    }
    /**
     * 对字符串加密，使用DES
     * @param str
     * @return
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     */
    public byte[] Encryptor(String str) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        //初始化 Cipher  ENCRYPT_MODE 表示加密模式
        c.init(Cipher.ENCRYPT_MODE,ddKey);
        // 使用 src 接收要加密的字符串
        byte[] src = str.getBytes();
        // 把加密后的数据放到 cipherByte 中
        cipherByte  = c.doFinal(src);
        return cipherByte;
    }

    /**
     * 对字符串进行解密，使用DES
     * @param buff
     * @return
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     */
    public byte[] Dncryptor(byte[] buff) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        //  初始化 Cipher ，DECRYPT_MODE表示解密
        c.init(Cipher.DECRYPT_MODE,ddKey);
        // 保存 机密后的字符串
        cipherByte = c.doFinal(buff);
        return  cipherByte;
    }

    public static void main(String[] args) throws  Exception {
        EncryptionDES  des = new EncryptionDES();
        String password = "xiaomi";
        byte[] enContext  = des.Encryptor(password);
        byte[] deContext = des.Dncryptor(enContext);

        System.out.println("明文："+password);
        System.out.println("加密后的字符串："+new String(enContext));
        System.out.println("解密后的字符串："+new String(deContext));
    }
}
